/*!
 * Treeview 1.5pre - jQuery plugin to hide and show branches of a tree
 * 
 * update by lin chaoqun 2011-12-08
 * v1.3.0
 * 基于Jquery.treeview二次开发
 * 1、支持checkbox, radio树
 * 2、支持JSON生成树
 * 3、支持checkbox/radio click事件回调
 * 4、支持自定义节点属性
 * 
 * JSON格式如下：
 * 
 * 数据格式：[{id:'', pid:'', text:'', attr: {自定义属性}}，{id:'', pid:'', text:'', attr: {自定义属性}}，……]
 * 自定义属性格式：{}
 */
;(function($) {

	// TODO rewrite as a widget, removing all the extra plugins
	$.extend($.fn, {
		swapClass: function(c1, c2) {
			var c1Elements = this.filter('.' + c1);
			this.filter('.' + c2).removeClass(c2).addClass(c1);
			c1Elements.removeClass(c1).addClass(c2);
			return this;
		},
		replaceClass: function(c1, c2) {
			return this.filter('.' + c1).removeClass(c1).addClass(c2).end();
		},
		hoverClass: function(className) {
			className = className || "hover";
			return this.hover(function() {
				$(this).addClass(className);
			}, function() {
				$(this).removeClass(className);
			});
		},
		heightToggle: function(animated, callback) {
			animated ?
				this.animate({ height: "toggle" }, animated, callback) :
				this.each(function(){
					jQuery(this)[ jQuery(this).is(":hidden") ? "show" : "hide" ]();
					if(callback)
						callback.apply(this, arguments);
				});
		},
		heightHide: function(animated, callback) {
			if (animated) {
				this.animate({ height: "hide" }, animated, callback);
			} else {
				this.hide();
				if (callback)
					this.each(callback);				
			}
		},
		prepareBranches: function(settings) {
			if (!settings.prerendered) {
				// mark last tree items
				this.filter(":last-child:not(ul)").addClass(CLASSES.last);
				// collapse whole tree, or only those marked as closed, anyway except those marked as open
				this.filter((settings.collapsed ? "" : "." + CLASSES.closed) + ":not(." + CLASSES.open + ")").find(">ul").hide();
			}
			// return all items with sublists
			return this.filter(":has(>ul)");
		},
		applyClasses: function(settings, toggler) {
			// TODO use event delegation
			/*this.filter(":has(>ul):not(:has(>a))").find(">span").unbind("click.treeview").bind("click.treeview", function(event) {
				// don't handle click events on children, eg. checkboxes
				if ( this == event.target )
					toggler.apply($(this).next());
			}).add( $("a", this) ).hoverClass();*/
			this.filter(":has(>ul):not(:has(>a))").find(">span").add( $("a", this) ).hoverClass();
			
			if (!settings.prerendered) {
				// handle closed ones first
				this.filter(":has(>ul:hidden)")
						.addClass(CLASSES.expandable)
						.replaceClass(CLASSES.last, CLASSES.lastExpandable);
						
				// handle open ones
				this.not(":has(>ul:hidden)")
						.addClass(CLASSES.collapsable)
						.replaceClass(CLASSES.last, CLASSES.lastCollapsable);
						
	            // create hitarea if not present
				var hitarea = this.find("div." + CLASSES.hitarea);
				if (!hitarea.length)
					hitarea = this.prepend("<div class=\"" + CLASSES.hitarea + "\"/>").find("div." + CLASSES.hitarea);
				hitarea.removeClass().addClass(CLASSES.hitarea).each(function() {
					var classes = "";
					$.each($(this).parent().attr("class").split(" "), function() {
						classes += this + "-hitarea ";
					});
					$(this).addClass( classes );
				})
			}
			
			// apply event to hitarea
			this.find("div." + CLASSES.hitarea).click( toggler );
		},
		treeview: function(settings) {
			
			settings = $.extend({
				cookieId: "treeview",
				persist: "location",
				type: "normal",
				skin: "default",
				wrap: "body",
				json: "",
				relation: true		//是否关联，关联情况下会对当前勾选对象的父与子元素自动勾选
			}, settings);
			
			
			settings.lastClickNode = null;
			
			(function(){
				if ( settings.toggle ) {
					var callback = settings.toggle;
					settings.toggle = function() {
						return callback.apply($(this).parent()[0], arguments);
					};
				}
				//radio回调函数
				if ( settings.radioCallBack ) {
					var callback1 = settings.radioCallBack;
					settings.radioCallBack = function() {
						return callback1.apply($(this).parent()[0], arguments);
					};
				}else{
					settings.radioCallBack = function(){};
				}
				//checkbox回调函数
				if ( settings.checkboxCallBack ) {
					var callback2 = settings.checkboxCallBack;
					settings.checkboxCallBack = function() {
						return callback2.apply($(this).parent()[0], arguments);
					};
				}else{
					settings.checkboxCallBack = function(){};
				}
				//node回调函数
				if ( settings.nodeCallBack ) {
					var callback3 = settings.nodeCallBack;
					settings.nodeCallBack = function() {
						return callback3.apply($(this).parent()[0], arguments);
					};
				}else{
					settings.nodeCallBack = function(){};
				}
			})();
			//创建treeview结构
			function createTreeView(wrap){
				if('' == settings.json){
					return;
				}
				var treeHTML = '';
				var json = settings.json;
				var len = 0;
				for(var i = 0, len = json.length; i < len; i ++){
					if(json[i].pid == null){
						treeHTML += '<li>' + getNodeCtrl(json[i], settings.type, i) + getNodeSpan(json[i], i) + '</li>';
						json.splice(i,1,null);
					}
				}
				json = clearEmptyArray(json).slice(0);
				var treeHTML = $(treeHTML);
				var doTime = 0;
				var len = json.length;
				do{
					treeHTML = innserChildNode(json, settings.type, treeHTML);
					json = clearEmptyArray(json).slice(0);
					doTime ++;
				}while(json.length > 0 && doTime <= len);
				
				$(wrap).append(treeHTML);
			}
			//插入子节点
			function innserChildNode(json, type, treeHTML){
				var ulObj = null;
				var liObj = null;
				var temHtml = '';
				var nodeID = '';
				for(var i = 0; i < json.length; i ++){
					if('' == json[i] || $('#tvNode_' + json[i].pid, treeHTML) == null){
						continue;
					}
					liObj = $('#tvNode_' + json[i].pid, treeHTML).parent('li');
					ulObj = liObj.children('ul');
					//追加nodeID 
					nodeID = $('#tvNode_' + json[i].pid, treeHTML).next().attr('nodeID') + '-' + (ulObj.children('li').length + 1);
					
					temHtml = getNodeSpan(json[i], nodeID);
					if(liObj.length > 0){
						if(ulObj.length > 0){
							ulObj.append('<li>' + getNodeCtrl(json[i], type, nodeID) + temHtml + '</li>');
							json.splice(i,1,null);
						}else{
							liObj.append('<ul></ul>');
							liObj.find('ul').append('<li>' + getNodeCtrl(json[i], type, nodeID) + temHtml + '</li>');
							json.splice(i,1,null);
						}
					}
				}
				return treeHTML;
			}
			//获取节点控件
			function getNodeCtrl(json, type, nodeID){
				var typeHTML = '';
				var tmpHTML = '';
				for(var r in json.attr){
					tmpHTML += r + '="' + json.attr[r] + '" ';
				}
				switch(type){
					case 'checkbox':
						typeHTML = '<input type="checkbox" id="tvNode_' + json.id + '" ' + tmpHTML + ' nodeID="' + nodeID + '"/>';
						break;
					case 'radio':
						typeHTML = '<input type="radio" id="tvNode_' + json.id + '" ' + tmpHTML + ' nodeID="' + nodeID + '"/>';
						break;
					case 'normal':
						typeHTML = '<span id="tvNode_' + json.id + '" ' + tmpHTML + ' nodeID="' + nodeID + '"></span>';
				}
				return typeHTML;
			}
			//获取节点span
			function getNodeSpan(json, nodeID){
				var html = [];
				var tmpHTML = [];
				for(var r in json.attr){
					tmpHTML.push(r, '="', json.attr[r], '" ');
				}
				html.push('<span nodeID="', nodeID, '" class="nodeName" nodevalue="', json.id, '" ', tmpHTML.join('') ,'>', json.text, '</span>');
				return html.join('');
			}
			//数组删除
			function clearEmptyArray(ary){
				var aryTmp = [];
				for(var i = 0, len = ary.length; i < len; i ++){
					!!ary[i] && aryTmp.push(ary[i]);
				}
				return aryTmp;
			}
			
			createTreeView(this);
		
			// factory for treecontroller
			function treeController(tree, control) {
				// factory for click handlers
				function handler(filter) {
					return function() {
						// reuse toggle event handler, applying the elements to toggle
						// start searching for all hitareas
						toggler.apply( $("div." + CLASSES.hitarea, tree).filter(function() {
							// for plain toggle, no filter is provided, otherwise we need to check the parent element
							return filter ? $(this).parent("." + filter).length : true;
						}) );
						return false;
					};
				}
				// click on first element to collapse tree
				$("a:eq(0)", control).click( handler(CLASSES.collapsable) );
				// click on second to expand tree
				$("a:eq(1)", control).click( handler(CLASSES.expandable) );
				// click on third to toggle tree
				$("a:eq(2)", control).click( handler() ); 
			}
		
			// handle toggle event
			function toggler() {
				$(this)
					.parent()
					// swap classes for hitarea
					.find(">.hitarea")
						.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
						.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
					.end()
					// swap classes for parent li
					.swapClass( CLASSES.collapsable, CLASSES.expandable )
					.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
					// find child lists
					.find( ">ul" )
					// toggle them
					.heightToggle( settings.animated, settings.toggle );
				if ( settings.unique ) {
					$(this).parent()
						.siblings()
						// swap classes for hitarea
						.find(">.hitarea")
							.replaceClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
							.replaceClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea )
						.end()
						.replaceClass( CLASSES.collapsable, CLASSES.expandable )
						.replaceClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
						.find( ">ul" )
						.heightHide( settings.animated, settings.toggle );
				}
			}
			this.data("toggler", toggler);
			
			function serialize() {
				function binary(arg) {
					return arg ? 1 : 0;
				}
				var data = [];
				branches.each(function(i, e) {
					data[i] = $(e).is(":has(>ul:visible)") ? 1 : 0;
				});
				$.cookie(settings.cookieId, data.join(""), settings.cookieOptions );
			}
			
			function deserialize() {
				var stored = $.cookie(settings.cookieId);
				if ( stored ) {
					var data = stored.split("");
					branches.each(function(i, e) {
						$(e).find(">ul")[ parseInt(data[i]) ? "show" : "hide" ]();
					});
				}
			}
			
			// add treeview class to activate styles
			this.addClass("treeview");
			
			// prepare branches and find all tree items with child lists
			var branches = this.find("li").prepareBranches(settings);
			
			switch(settings.persist) {
			case "cookie":
				var toggleCallback = settings.toggle;
				settings.toggle = function() {
					serialize();
					if (toggleCallback) {
						toggleCallback.apply(this, arguments);
					}
				};
				deserialize();
				break;
			case "location":
				var current = this.find("a").filter(function() {
					return this.href.toLowerCase() == location.href.toLowerCase();
				});
				if ( current.length ) {
					// TODO update the open/closed classes
					var items = current.addClass("selected").parents("ul, li").add( current.next() ).show();
					if (settings.prerendered) {
						// if prerendered is on, replicate the basic class swapping
						items.filter("li")
							.swapClass( CLASSES.collapsable, CLASSES.expandable )
							.swapClass( CLASSES.lastCollapsable, CLASSES.lastExpandable )
							.find(">.hitarea")
								.swapClass( CLASSES.collapsableHitarea, CLASSES.expandableHitarea )
								.swapClass( CLASSES.lastCollapsableHitarea, CLASSES.lastExpandableHitarea );
					}
				}
				break;
			}
			
			branches.applyClasses(settings, toggler);
				
			// if control option is set, create the treecontroller and show it
			if ( settings.control ) {
				treeController(this, settings.control);
				$(settings.control).show();
			}
			//radio check事件绑定
			switch(settings.type){
				case 'checkbox':
					branches.checkboxHandle(this, settings);
					break;
				case 'radio':
					branches.radioHandle(this, settings);
					break;
				case 'normal':
					//branches.nodeHandle(this, settings);
					//留空，以便扩展
			}
			
			branches.nodeHandle(this, settings);
			return this;
		},
		//radio处理
		radioHandle: function(tree, settings){
			tree.find(':radio').click(function(){
				var me = $(this);
				/*if(settings.relation){
					//保留空接口
					var me = $(this);
		            var lis = me.parents('li');
					for(var i = 1; i < lis.length; i ++){
					    lis.eq(i).children(':radio').attr('checked',true);
					}
					lis.eq(0).siblings().find(':radio').attr('checked',false);
				}*/
				settings.radioCallBack(me);
	        });
		},
		//checkbox处理
		checkboxHandle: function(tree, settings){
			tree.find(':checkbox').click(function(){
				var me = $(this);
				if(settings.relation){
		            var lis = me.parents('li');
				    if(me.attr('checked')) {
					    lis.eq(0).find(':checkbox').attr('checked',true);
					    for(var i = 1; i < lis.length; i ++){
					        lis.eq(i).children(':checkbox').attr('checked',true);
					    }
				    } else {
					    lis.eq(0).find(':checkbox').attr('checked',false);
					    for(var i = 0; i < lis.length; i ++){
					        if(lis.eq(i).parent('ul').find(':checked').length == 0){
					            lis.eq(i + 1).children(':checkbox').attr('checked',false);
					        }
					    }
				    }
				}
				settings.checkboxCallBack(me);
	        });
		},
		//node处理
		nodeHandle: function(tree, settings){
			tree.find('span.nodeName').click(function(){
				var me = $(this);
				if(settings.lastClickNode != null){
					settings.lastClickNode.css('color','');
				}
				me.css('color', 'red');
				settings.lastClickNode = me;
				settings.nodeCallBack(me);
	        });
		}
	});
	
	// classes used by the plugin
	// need to be styled via external stylesheet, see first example
	$.treeview = {};
	var CLASSES = ($.treeview.classes = {
		open: "open",
		closed: "closed",
		expandable: "expandable",
		expandableHitarea: "expandable-hitarea",
		lastExpandableHitarea: "lastExpandable-hitarea",
		collapsable: "collapsable",
		collapsableHitarea: "collapsable-hitarea",
		lastCollapsableHitarea: "lastCollapsable-hitarea",
		lastCollapsable: "lastCollapsable",
		lastExpandable: "lastExpandable",
		last: "last",
		hitarea: "hitarea"
	});
	
})(jQuery);